#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>

#define SHMSIZE 4096
#define PATHNAME "."
#define PROJ_ID 0x5555

int getKey(const char* pathname,int id)
{
    int key = ftok(pathname,id);
    if(key == -1)
    {
        perror("getKey filed");
        exit(1);
    }
    return key;
}

int getShmHelper(int key,int size,int flag)
{
    int shmid = shmget(key,size,flag);
    if(shmid == -1)
    {
        perror("getShmHelper filed");
        exit(1);
    }
    return shmid;
}

int creatShm(int size)
{
    int key = getKey(PATHNAME,PROJ_ID);
    int shmid = getShmHelper(key,size,IPC_CREAT | IPC_EXCL | 0666);
    return shmid;
}

int getShm(int size)
{
    int key = getKey(PATHNAME,PROJ_ID);
    int shmid = getShmHelper(key,size,IPC_CREAT);
    return shmid;
}

char* attachShm(int shmid)
{
    //0对共享内存有读写权限
    char* start = (char*)shmat(shmid,nullptr,0);
    if(start == (char*) -1)
    {
        perror("attachShm");
        exit(1);
    }
    return start;
}

void detachShm(char* start)
{
    int n = shmdt(start);
    if(n == -1)
    {
        perror("detach filed");
        exit(1);
    }
}

void delShm(int shmid)
{
    int n = shmctl(shmid,IPC_RMID,nullptr);
    if(n == -1)
    {
        perror("delShm filed");
        exit(1);
    }
}
